package com.lxyk.yygh.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.lxyk.yygh.oss.service.FileService;
import com.lxyk.yygh.oss.utils.ConstantOssPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    //上传文件到阿里云OSS
    @Override
    public String upload(MultipartFile file) {
        // Endpoint以广州为例，其它Region请按实际情况填写。
        String ednpoint = ConstantOssPropertiesUtils.EDNPOINT;
        String accessKeyId = ConstantOssPropertiesUtils.ACCESS_KEY_ID;
        String secrect = ConstantOssPropertiesUtils.SECRECT;
        String bucket = ConstantOssPropertiesUtils.BUCKET;

        //创建OssClient实例
        OSS ossClient = new OSSClientBuilder().build(ednpoint, accessKeyId, secrect);

        try {
            //上传文件流。
            InputStream inputStream = file.getInputStream();
            String fileName = file.getOriginalFilename();

            //生成随机唯一值，使用uuid，添加到文件名称里面
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName=uuid+fileName;
            //按照当前日期，创建文件夹，上传到创建文件夹里面
            //  2021/02/02/01.jpg
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName= timeUrl + "/" + fileName;

            //调用方法实现上传
            ossClient.putObject(bucket,fileName,inputStream);
            //关闭ossClient
            ossClient.shutdown();
            //上传之后文件路径
            //https://yygh-yyghwqbgz.oss-cn-guangzhou.aliyuncs.com/2023/07/15/39c9fe14539e4653a72f0e740f3ac322头像.jpg
            String url = "https://"+bucket+"."+ednpoint+"/"+fileName;
            //返回路径
            return url;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
